<template>
  <div id="app">
    <header class="app-header">
      数据手套人机交互系统Web端
    </header>
    <div class="container">
      <div class="left-panel">
        <!-- 左侧顶部导航菜单 -->
        <div class="menu-container">
          <div class="menu-bar">
            <button
                :class="{ 'active': currentTab === 'server' }"
                @click="currentTab = 'server'"
            >
              服务器连接
            </button>
            <button
                :class="{ 'active': currentTab === 'control' }"
                @click="currentTab = 'control'"
            >
              实时控制
            </button>
            <button
                :class="{ 'active': currentTab === 'analysis' }"
                @click="currentTab = 'analysis'"
            >
              数据分析
            </button>
          </div>
        </div>

        <!-- 内容展示区域 -->
        <div class="content-container-fixed">
          <!-- 服务器连接模块 -->
          <div v-show="currentTab === 'server'">
            <table class="device-table">
              <thead>
              <tr>
                <th colspan="2">MQTT连接设置</th>
              </tr>
              </thead>
              <tbody>
              <tr>
                <td>连接状态</td>
                <td>
                  <button class="connect-btn" @click="connectMqtt">
                    {{ mqttConnected ? '断开MQTT' : '连接MQTT' }}
                  </button>
                  <span :class="['status-dot', mqttConnected ? 'online' : 'offline']"></span>
                  <span>{{ mqttConnected ? '已连接' : '未连接' }}</span>
                </td>
              </tr>
              <tr>
                <td>订阅话题</td>
                <td>
                  <input
                      v-model="subscribeTopic"
                      placeholder="请输入要订阅的话题"
                      class="topic-input"
                  />
                  <button class="connect-btn" @click="subscribeTopicFn" :disabled="!mqttConnected">
                    订阅
                  </button>
                </td>
              </tr>
              </tbody>
            </table>
          </div>

          <!-- 实时控制模块 -->
          <div v-show="currentTab === 'control'">
            <table class="device-table">
              <thead>
              <tr>
                <th colspan="2">实时控制</th>
              </tr>
              </thead>
              <tbody>
              <tr>
                <td>实时控制</td>
                <td>
                  <label class="switch">
                    <input type="checkbox" v-model="realtimeControl" :disabled="!mqttConnected">
                    <span class="slider"></span>
                  </label>
                  <span>{{ realtimeControl ? '开启' : '关闭' }}</span>
                </td>
              </tr>
              <tr>
                <td>功能按钮</td>
                <td>
                  <div class="function-buttons">
                    <button class="connect-btn" @click="increaseDevice">增加</button>
                    <button class="connect-btn" @click="decreaseDevice">减小</button>
                  </div>
                </td>
              </tr>
              <tr>
                <td>手掌压力</td>
                <td>
                  <div class="hand-pressure-container">
                    <img :src="require('/src/assets/hand_outline.png')" alt="Hand Outline" class="hand-image" />
                    <div
                        v-for="(finger, index) in fingerPressures"
                        :key="index"
                        class="pressure-point"
                        :style="{
                          top: finger.y + 'px',
                          left: finger.x + 'px',
                          backgroundColor: getPressureColor(finger.pressure)
                        }"
                    >
                      <span class="pressure-value">{{ finger.pressure }}</span>
                    </div>
                  </div>
                </td>
              </tr>
              </tbody>
            </table>
          </div>

          <!-- 数据分析模块 -->
          <div v-show="currentTab === 'analysis'">
            <div id="pressure-chart" style="width: 100%; height: 500px;"></div>
            <div class="analysis-actions">
              <button class="connect-btn" @click="exportToCSV">保存数据</button>
            </div>
          </div>
        </div>
      </div>
      <!-- 右侧3D模型区域 -->
      <div class="right-panel">
        <ThreeModelLoader ref="threeModelRef" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch  } from 'vue'
import ThreeModelLoader from './components/ThreeModelLoader.vue'
import request from '/utils/request'
import { connectWebSocket, disconnectWebSocket, onMqttData } from '/utils/websocket'
import { ElMessage } from 'element-plus' // 引入 ElMessage
import * as echarts from 'echarts'
// 新增当前标签状态
const currentTab = ref('server')

// 响应式数据
const mqttConnected = ref(false)
const subscribeTopic = ref('test/topic1')
const realtimeControl = ref(false)
const threeModelRef = ref(null)
const fingerPressures = ref([
  { id: 'thumb', x: 350, y: 280, pressure: 0 }, // 拇指
  { id: 'index', x: 270, y: 140, pressure: 0 }, // 食指
  { id: 'middle', x: 200, y: 110, pressure: 0 }, // 中指
  { id: 'ring', x: 140, y: 140, pressure: 0 }, // 无名指
  { id: 'pinky', x: 90, y: 180, pressure: 0 },  // 小指
  { id: 'zhang1', x: 300, y: 340, pressure: 0 }, // 掌部一
  { id: 'zhang2', x: 240, y: 380, pressure: 0 }, // 掌部二
  { id: 'zhang3', x: 170, y: 370, pressure: 0 }, // 掌部三
  { id: 'zhang4', x: 130, y: 320, pressure: 0 } // 掌部四
])
// 在响应式数据部分添加
const pressureChart = ref(null)
const pressureHistory = ref({
  thumb: [],
  index: [],
  middle: [],
  ring: [],
  pinky: [],
  zhang1: [],
  zhang2: [],
  zhang3: [],
  zhang4: []
})

// 处理 MQTT 数据
const handleMqttData = (data) => {
  if (data.tab!== undefined) {
    // 处理坐标数据
    const { tab, x, y, z } = data
    console.log('解构后的坐标:', { tab, x, y, z })
    if (threeModelRef.value?.setBoneRotation) {
      threeModelRef.value.setBoneRotation(tab, x, y, z)
    } else {
      console.error('Three.js组件或方法未就绪')
    }
  }
  // 处理压力数据
  const fingerPressureMap = {
    'F0': 'thumb',
    'F1': 'index',
    'F2': 'middle',
    'F3': 'ring',
    'F4': 'pinky',
    'F5': 'zhang1',
    'F6': 'zhang2',
    'F7': 'zhang3',
    'F8': 'zhang4'
  }
  Object.keys(fingerPressureMap).forEach(key => {
    if (data[key]!== undefined) {
      const fingerId = fingerPressureMap[key]
      const history = pressureHistory.value[fingerId]
      history.push(data[key])
      if (history.length > 50) { // 保留最近50个数据点
        pressureHistory.value[fingerId] = history.slice(-50)
      }
      const finger = fingerPressures.value.find(f => f.id === fingerId)
      if (finger) {
        finger.pressure = Math.min(Math.max(data[key], 0), 5)
        console.log(`更新 ${fingerId} 压力值为: ${finger.pressure}`)
      }
    }
  })
  updatePressureChart()
}
const updatePressureChart = () => {
  if (!pressureChart.value || pressureChart.value.isDisposed()) { // 添加实例状态检查
    console.error('图表实例未初始化或已销毁')
    return
  }
  const option = {
    // 设置标题位置，让标题居上且居中显示
    title: {
      text: '手指压力变化曲线',
      left: 'center',
      top: '5%'
    },
    tooltip: {
      trigger: 'axis'
    },
    // 设置图例位置，让图例在标题下方且居中显示
    legend: {
      data: ['拇指', '食指', '中指', '无名指', '小指', '掌部1', '掌部2', '掌部3', '掌部4'],
      left: 'center',
      top: '12%' // 调整顶部位置，使其位于标题下方
    },
    // 调整 grid 区域的上边距，避免与标题和图例重叠
    grid: {
      left: '3%',
      right: '4%',
      top: '20%', // 增大顶部边距，为标题和图例留出空间
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: Array.from({length: 50}, (_, i) => i),
      name: '时间序列', // 添加 X 轴标签
      nameLocation: 'middle', // 设置标签位置在轴中间
      nameGap: 30 // 设置标签与轴的间距
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 5,
      name: '压力值（/N）', // 添加 Y 轴标签
      nameLocation: 'middle', // 设置标签位置在轴中间
      nameRotate: 90, // 设置标签旋转 90 度
      nameGap: 15 // 设置标签与轴的间距
    },
    series: [
      {
        name: '拇指',
        type: 'line',
        data: pressureHistory.value.thumb
      },
      {
        name: '食指',
        type: 'line',
        data: pressureHistory.value.index
      },
      {
        name: '中指',
        type: 'line',
        data: pressureHistory.value.middle
      },
      {
        name: '无名指',
        type: 'line',
        data: pressureHistory.value.ring
      },
      {
        name: '小指',
        type: 'line',
        data: pressureHistory.value.pinky
      },
      {
        name: '掌部1',
        type: 'line',
        data: pressureHistory.value.zhang1
      },
      {
        name: '掌部2',
        type: 'line',
        data: pressureHistory.value.zhang2
      },
      {
        name: '掌部3',
        type: 'line',
        data: pressureHistory.value.zhang3
      },
      {
        name: '掌部4',
        type: 'line',
        data: pressureHistory.value.zhang4
      }
    ]
  }

  // 打印配置项，检查是否有 undefined 值
  console.log('图表配置项:', option)
  pressureChart.value.setOption(option)
}



// 连接 MQTT
const connectMqtt = async () => {
  if (!mqttConnected.value) {
    try {
      const response = await request.post('/api/devices/mqttconnect')
      console.log('连接:', response)
      if (response && response.success) {
        mqttConnected.value = true
        ElMessage.success('MQTT连接成功')
      } else {
        mqttConnected.value = false
        ElMessage.error('MQTT连接失败')
      }
    } catch {
      mqttConnected.value = false
      ElMessage.error('MQTT连接异常')
    }
  } else {
    try {
      const response = await request.post('/api/devices/mqttdisconnect')
      if (response && response.success) {
        mqttConnected.value = false
        ElMessage.info('MQTT已断开')
      }
    } catch {
      ElMessage.error('MQTT断开异常')
    }
  }
}

// 订阅话题
const subscribeTopicFn = async () => {
  try {
    const response = await request.post('/api/devices/mqttsubscribe', { topic: subscribeTopic.value })
    if (response && response.success) {
      console.log('订阅成功')
      ElMessage.success('订阅成功')
    } else {
      console.log('订阅失败')
      ElMessage.success('订阅失败')
    }
  } catch {
    console.log('订阅异常')
    ElMessage.success('订阅失败')
  }
}

// 增加设备
const increaseDevice = async () => {
  try {
    const response = await request.post('/api/devices/increase')
    console.log('增加指令响应:', response)
    if (response.data) {
      const { x, y, z } = response.data
      threeModelRef.value.setBoneRotation('upperarm01R', x, y, z)
      if (fingerPressures.value[0]) {
        fingerPressures.value[0].pressure = Math.min(fingerPressures.value[0].pressure + 0.5, 5)
      }
    }
  } catch (error) {
    console.error('调用失败:', error)
  }
}

// 减小设备
const decreaseDevice = async () => {
  try {
    const response = await request.post('/api/devices/decrease')
    console.log('减少指令响应:', response)
    if (response.data) {
      const { x, y, z } = response.data
      threeModelRef.value.setBoneRotation('upperarm01R', x, y, z)
      if (fingerPressures.value[0]) {
        fingerPressures.value[0].pressure = Math.max(fingerPressures.value[0].pressure - 0.5, 0)
      }
    }
  } catch (error) {
    console.error('调用失败:', error)
  }
}

// 根据压力值获取颜色
const getPressureColor = (pressure) => {
  const maxPressure = 5
  const normalizedPressure = Math.min(Math.max(pressure, 0), maxPressure) / maxPressure
  let r, g, b = 0
  if (normalizedPressure < 0.5) {
    r = Math.floor(255 * normalizedPressure * 2)
    g = 255
  } else {
    r = 255
    g = Math.floor(255 * (1 - (normalizedPressure - 0.5) * 2))
  }
  return `rgb(${r}, ${g}, ${b})`
}

// 监听实时控制开关变化
watch(realtimeControl, async (val) => {
  if (mqttConnected.value) {
    try {
      const response = await request.post('/api/devices/realtime', { enable: val })
      console.log('实时控制响应:', response)
      if (!(response && response.success)) {
        realtimeControl.value =!val
      }
    } catch {
      console.error('实时控制请求失败')
      // realtimeControl.value =!val // 恢复开关状态
    }
  }
})

onMounted(() => {
  connectWebSocket()
  // const resizeObserver = new ResizeObserver(entries => {
  //   if (entries[0].contentRect.width > 0 && entries[0].contentRect.height > 0) {
  //     initChart()
  //   }
  // })
  const resizeObserver = new ResizeObserver(entries => {
    if (pressureChart.value && !pressureChart.value.isDisposed()) {
      handleResize() // 直接触发 resize 处理
    } else if (entries[0].contentRect.width > 0) {
      initChart() // 仅在未初始化时执行初始化
    }
  })
  const chartDom = document.getElementById('pressure-chart')
  if (chartDom) {
    resizeObserver.observe(chartDom)
  }

  // 使用setTimeout确保DOM完全渲染
  setTimeout(() => {
    const chartDom = document.getElementById('pressure-chart')
    if (chartDom && chartDom.clientWidth > 0 && chartDom.clientHeight > 0) {
      pressureChart.value = echarts.init(chartDom)
      window.addEventListener('resize', handleResize)
      updatePressureChart()
    } else {
      setTimeout(initChart, 100)
    }
  }, 100)

  const unsubscribe = onMqttData(handleMqttData)
  onBeforeUnmount(() => {
    unsubscribe()
    disconnectWebSocket()
    if (pressureChart.value) {
      window.removeEventListener('resize', handleResize)
      pressureChart.value.dispose()
    }
  })
})

// 添加独立的初始化函数
const initChart = () => {
  const chartDom = document.getElementById('pressure-chart')
  if (chartDom && chartDom.clientWidth > 0 && chartDom.clientHeight > 0) {
    pressureChart.value = echarts.init(chartDom)
    window.addEventListener('resize', handleResize)
    updatePressureChart()
  } else {
    setTimeout(initChart, 100)
  }
}
// 添加 resize 处理函数
const handleResize = () => {
  if (pressureChart.value && !pressureChart.value.isDisposed()) { // 添加销毁状态检查
    pressureChart.value.resize()
  }
}
const exportToCSV = () => {
  // 创建CSV标题行
  let csvContent = "时间戳,拇指,食指,中指,无名指,小指,掌部1,掌部2,掌部3,掌部4\n"

  // 获取最大数据长度
  const maxLength = Math.max(...Object.values(pressureHistory.value).map(arr => arr.length))

  // 生成数据行
  for(let i = 0; i < maxLength; i++) {
    const row = [
      new Date().toISOString(), // 这里可以替换为实际的时间戳
      pressureHistory.value.thumb[i] || 0,
      pressureHistory.value.index[i] || 0,
      pressureHistory.value.middle[i] || 0,
      pressureHistory.value.ring[i] || 0,
      pressureHistory.value.pinky[i] || 0,
      pressureHistory.value.zhang1[i] || 0,
      pressureHistory.value.zhang2[i] || 0,
      pressureHistory.value.zhang3[i] || 0,
      pressureHistory.value.zhang4[i] || 0
    ].join(',')

    csvContent += row + '\n'
  }

  // 创建下载链接
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.setAttribute('href', url)
  link.setAttribute('download', `pressure_data_${new Date().getTime()}.csv`)
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}



</script>

<style scoped>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  color: #2c3e50;
  margin: 0;
  padding: 0;
  background: #f0f2f5;
  height: 100vh;
}
.app-header {
  width: 100%;
  background: linear-gradient(90deg, #1976d2 0%, #42a5f5 100%);
  color: #fff;
  font-size: 2rem;
  font-weight: bold;
  letter-spacing: 2px;
  text-align: center;
  padding: 10px 0 10px 0;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}
.container {
  display: flex;
  height: calc(100vh - 70px);
}


.menu-bar button.active {
  background: #fff;
  font-weight: bold;
  border-left: 2px solid #42a5f5;
  border-bottom: none; /* 移除底部边框 */
}
.menu-bar button:hover {
  background: #e6e6e6;
}

.right-panel {
  flex: 1 1 50%;
  width: 50%;
  background: #000;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
}
.device-table {
  width: 100%;
  border-collapse: collapse;
  background: #fff;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.device-table th {
  background: #00772e;
  color: #fff;
  font-weight: 600;
  padding: 12px 8px;
  border: none;
}
.device-table td {
  border-bottom: 1px solid #e0e0e0;
  padding: 10px 8px;
  text-align: center;
  background: #fafbfc;
}
.status-dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin: 0 6px;
  vertical-align: middle;
}
.status-dot.online {
  background: #4caf50;
}
.status-dot.offline {
  background: #f44336;
}
.topic-input {
  padding: 4px 8px;
  border: 1px solid #ccc;
  border-radius: 3px;
  margin-right: 8px;
}
.switch {
  position: relative;
  display: inline-block;
  width: 40px;
  height: 22px;
  vertical-align: middle;
  margin-right: 8px;
}
.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}
.slider {
  position: absolute;
  cursor: pointer;
  top: 0; left: 0; right: 0; bottom: 0;
  background-color: #ccc;
  border-radius: 22px;
  transition: .4s;
}
.slider:before {
  position: absolute;
  content: "";
  height: 16px; width: 16px;
  left: 3px; bottom: 3px;
  background-color: white;
  border-radius: 50%;
  transition: .4s;
}
.switch input:checked + .slider {
  background-color: #42a5f5;
}
.switch input:checked + .slider:before {
  transform: translateX(18px);
}
.device-table tr:last-child td {
  border-bottom: none;
}
.connect-btn {
  background: #42a5f5;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 6px 14px;
  cursor: pointer;
  transition: background 0.2s;
  margin-right: 8px;
}
.connect-btn:hover {
  background: #1976d2;
}

.menu-bar {
  display: flex;
  background: #f0f2f5;
  border-bottom: 1px solid #e0e0e0;
}

.menu-bar button {
  flex: 1;
  padding: 12px;
  border: none;
  background: transparent;
  cursor: pointer;
  transition: background 0.2s;
}

/* 新增手掌图片和压力点样式 */
.hand-pressure-container {
  position: relative; /* 改为相对定位，使其在 left-panel 中按文档流排列 */
  margin-top: 20px; /* 与上方按钮区域的间距 */
  width: 500px; /* 根据图片实际大小调整 */
  height: 500px; /* 根据图片实际大小调整 */
  display: flex;
  justify-content: center;
  align-items: center;
  /* background-color: rgba(255, 255, 255, 0.1); /* 调试用背景 */
}

.hand-image {
  width: 100%;
  height: 100%;
  object-fit: contain; /* 保持图片比例 */
  position: absolute; /* 确保图片在容器内 */
}

.pressure-point {
  position: absolute;
  width: 40px; /* 压力点大小 */
  height: 40px; /* 压力点大小 */
  border-radius: 50%; /* 圆形 */
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 0.8em;
  font-weight: bold;
  opacity: 0.7; /* 透明度 */
  transition: background-color 0.5s ease; /* 颜色渐变动画 */
  border: 2px solid rgba(255, 255, 255, 0.5); /* 边框 */
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.3); /* 阴影 */
}

.pressure-value {
  text-shadow: 1px 1px 2px rgba(0,0,0,0.5); /* 文字阴影，提高可读性 */
}

/* 调整功能按钮区域的样式，使其与手掌容器对齐 */
.function-buttons {
  width: 100%; /* 让按钮区域占据 left-panel 的全部宽度 */
  display: flex;
  justify-content: center; /* 按钮居中 */
  padding: 10px 0; /* 增加一些内边距 */
  background: #fafbfc; /* 与表格背景色一致 */
  box-shadow: 0 2px 4px rgba(0,0,0,0.02); /* 轻微阴影 */
  border-bottom: 1px solid #e0e0e0; /* 底部边框 */
}

#pressure-chart {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
/* 修改菜单容器样式 */
.menu-container {
  width: 100%;
  background: #f0f2f5;
  border-bottom: 1px solid #e0e0e0;
}

.menu-bar {
  display: flex;
  flex-direction: row; /* 改为水平排列 */
  padding: 0 20px;
}

/* 调整左侧面板布局 */
.left-panel {
  width: 50%;
  display: flex;
  flex-direction: column;
}

.content-container-fixed {
  height: calc(100vh - 70px - 48px); /* 70px header + 48px menu */
}

.analysis-actions {
  margin-bottom: 20px;
  text-align: right;
  padding: 10px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
</style>

